package com.happts.Dao;

import com.happts.Entity.USER;
import com.happts.Utils.JDBCManager;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class USERDAO {

    public boolean insert(USER user){
        String sql = "insert into USER values(?,?)";
        Object[] params = {
                user.getUsername(),
                user.getPassword()
        };
        return JDBCManager.executeSQL(sql,params);
    }

    public boolean delete(USER user){
        String sql = "DELETE FROM USER WHERE username=?";
        Object[] params = {user.getUsername()};
        return JDBCManager.executeSQL(sql,params);
    }

    public List<USER> findAll(){
        String sql = "SELECT * FROM USER";
        ResultSet resultSet = JDBCManager.executeQuery(sql);
        return resultSetToList(resultSet);
    }

    public List<USER> findOne(String username){
        String sql = "SELECT * FROM USER WHERE username=?";
        Object[] params = {username};
        ResultSet resultSet = JDBCManager.executeQuery(sql,params);
        return resultSetToList(resultSet);
    }

    private List<USER> resultSetToList(ResultSet resultSet){
        List<USER> recordList = new ArrayList<>();
        try {
            while (resultSet.next()){
                USER user = new USER(resultSet.getString("username"),
                        resultSet.getString("password"));
                recordList.add(user);
            }
        }catch (SQLException e){
            e.printStackTrace();
        }
        return recordList;
    }
}
